package com.cloudcc.mobile.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;

import com.lidroid.xutils.http.client.multipart.MultipartEntity;
import com.lidroid.xutils.http.client.multipart.content.FileBody;

public class NetWork {
	private static final String CHARSET = HTTP.UTF_8;
	public static HttpClient httpClient;
	public static String get(String url){
		// HttpGet连接对象
		HttpGet httpRequest=new HttpGet(url);
		HttpClient httpclient = null;
		String strResult="";

		try {
			//计算网络超时用
			HttpParams httpParams = new BasicHttpParams(); 
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 10000);
			//取得HttpClient对象
			httpclient=new DefaultHttpClient(httpParams);
			HttpResponse httpResponse=httpclient.execute(httpRequest);
			//请求HttpCLient，取得HttpResponse
			//请求成功
			if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//取得返回的字符串
				return EntityUtils.toString(httpResponse.getEntity());
			}else{
				return null;
			}
		}catch(ConnectTimeoutException e){
			Tools.handle(e);
			return "outTime";
		} catch(SocketTimeoutException e){
			Tools.handle(e);
			return "outTime";
		}catch (ClientProtocolException e) {
			Tools.handle(e);
			return "outTime";
		} catch (IOException e) {
			Tools.handle(e);
			return "NetworkError";
		}finally{  
			httpclient.getConnectionManager().shutdown();  
		}  
	}

	/**
	 * post请求
	 * @param url
	 * @param pairs
	 * @return
	 */
	public static String post(String url, List<NameValuePair> pairs) {
		//计算网络超时用
		HttpParams httpParams = new BasicHttpParams(); 
		HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
		HttpConnectionParams.setSoTimeout(httpParams, 10000);
		HttpClient client = new DefaultHttpClient(httpParams);
		HttpPost post = new HttpPost(url);
		try {
			if (pairs != null) {
				HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
				post.setEntity(entity);
			}
			HttpResponse response = client.execute(post);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				return EntityUtils.toString(response.getEntity());
			}
		} catch (Exception e) {
			Tools.handle(e);
			return "";
		}finally{  
			client.getConnectionManager().shutdown();  
		}  
		return "";
	}
	public static HttpClient getHttp(){
		if(null==httpClient){
			HttpParams params =new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params,
					CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams
			.setUserAgent(
					params,
					"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
							+"AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 3000);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 10000);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 8000);

			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg =new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			//schReg.register(new Scheme("https", SSLSocketFactory
				//	.getSocketFactory(), 443));
			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr =new ThreadSafeClientConnManager(
					params, schReg);
			httpClient= new DefaultHttpClient(conMgr,params);
		}
		return httpClient;
	}

	/**
	 * 上传文件
	 * @param file 文件
	 * @param url 地址
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String postFile(File file,String url) throws ClientProtocolException, IOException {  
		FileBody bin = null;
		HttpClient httpclient;  
		//		HttpClient httpclient = getHttp();  
		HttpPost httppost = new HttpPost(url);  

		//计算网络超时用
		HttpParams httpParams = new BasicHttpParams(); 
		HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
		HttpConnectionParams.setSoTimeout(httpParams, 10000);
		//取得HttpClient对象
		httpclient=new DefaultHttpClient(httpParams);
		if(file != null) {  
			bin = new FileBody(file);  
		}  
		MultipartEntity reqEntity = new MultipartEntity();  
		reqEntity.addPart("upfile", bin); 
		httppost.setEntity(reqEntity);  
		HttpResponse response = httpclient.execute(httppost);  
		HttpEntity resEntity = response.getEntity();  
		if (resEntity != null) {  
			String resultStr = EntityUtils.toString(resEntity);
			resEntity.consumeContent();  
			return resultStr;
		}  
		return null;  
	}  
	/**
	 * 判断是否有网
	 * @param act
	 * @return
	 */
	public static boolean detect(Context act) {  

		ConnectivityManager manager = (ConnectivityManager) act  
				.getApplicationContext().getSystemService(  
						Context.CONNECTIVITY_SERVICE);  
		if (manager == null) {  
			return false;  
		}  
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();  
		if (networkinfo == null || !networkinfo.isAvailable()) { 
			return false;  
		}  

		return true;  
	} 

	public void checkNetState(final Context context){
		@SuppressWarnings("static-access")
		ConnectivityManager manager=(ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
		NetworkInfo activityNetworkInfo=manager.getActiveNetworkInfo();
		if (activityNetworkInfo==null||!activityNetworkInfo.isAvailable()){
			//显示对话框，让用户去设置风络
			AlertDialog.Builder dialog=new AlertDialog.Builder(context);
			dialog.setTitle("打开网络");
			dialog.setMessage("当前没有网络，请打开网络");
			dialog.setPositiveButton("设置", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						Intent intent=new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
						context.startActivity(intent);
						dialog.dismiss();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}});

			dialog.setNegativeButton("不设置", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						dialog.dismiss();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}});
			dialog.show();
		}
	}

	/**
	 * @param url 请求地址 
	 * @param filePath 文件在服务器保存路径（这里是为了自己测试方便而写，可以将该参数去掉）
	 * @return 
	 * @throws IOException    
	 */
	@SuppressLint("SimpleDateFormat")
	public static String uploadFile(String url, String filePath){
		long a=System.currentTimeMillis();
		InputStream inputStream = null;
		String result = null; 
		try {
//			Bitmap bitmap=ImageUtils.getimage(filePath);
//			byte[] imagebyte=ImageUtils.BitmaptoBytes(bitmap);
			
			Bitmap bitmap=ImageUtils.getImg(filePath,480f,800f);
			byte[] imagebyte=ImageUtils.compressBitmap(bitmap,100f);
			
			SimpleDateFormat formatter=new SimpleDateFormat ("yyyyMMddHHmmss");     
			Date curDate= new Date(System.currentTimeMillis());//获取当前时间     
			String   time=formatter.format(curDate);
			String picPath=ImageUtils.SaveImage(time+".jpg", imagebyte);
			File file = new File(picPath);
			if (!file.exists() || !file.isFile()) {
				return null;
			}

			/**
			 * 第一部分
			 */
			URL urlObj = new URL(url);
			HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

			/**
			 * 设置关键值
			 */
			con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			con.setConnectTimeout(30000);//超时时间
			con.setReadTimeout(30000);
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");

			// 设置边界   // shijianchu
			String BOUNDARY = "----------" + System.currentTimeMillis();
			con.setRequestProperty("Content-Type", "multipart/mixed; boundary="
					+ BOUNDARY);
			// 第一部分：
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // ////////必须多两道线
			sb.append(BOUNDARY);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name=\"file\";filename=\""
					+ file.getName() + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] head = sb.toString().getBytes("utf-8");
			// 获得输出流
			OutputStream out = new DataOutputStream(con.getOutputStream());
			out.write(head);
			OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
			// 文件正文部分
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();
			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();
			//删除这个文件
			String imagepath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/CloudCC/Download/"+time+".jpg";
			FileUtil.deleteFile(imagepath);
			/**
			 * 读取服务器响应，必须读取,否则提交不成功
			 */
			int res= con.getResponseCode();
			if(res!=200){
				return null;
			}
			inputStream =con.getInputStream();
//			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8*1024); //强制缓存大小为16KB，一般Java类默认为8KB
			 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); 
			
			StringBuilder sbString = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {  //处理换行符
				sbString.append(line + "\n");  
			}
			reader.close(); 
			inputStream.close();
			con.disconnect();  
			return sbString.toString();
		} catch(Exception e){
			Tools.i("outtime", "ConnectTimeoutException");
			Tools.handle(e);
			return "null";
		} 
	}


	public static Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 480;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}
}
